"""
股票数据处理器
负责股票数据的初始化、更新和管理
"""

import logging
from datetime import datetime, timedelta
from typing import List, Dict, Optional
import time

from src.stock.api import AKShareAPI
from src.database.data_manager import DataManager
from .data_processor import StockDataProcessor

logger = logging.getLogger(__name__)

class StockManager:
    _instance = None
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance._initialized = False
        return cls._instance
    
    def __init__(self):
        if not self._initialized:
            self.data_processor = None
            self.data_manager = None
            self.MARKET_CLOSE_TIME = "15:10:00"
            self._initialized = True
            
    @classmethod
    def get_instance(cls):
        if cls._instance is None:
            cls._instance = cls()
        return cls._instance
        
    def initialize(self) -> bool:
        """初始化处理器，检查数据库状态"""
        try:
            # 使用DataManager的单例
            if not self.data_manager:
                self.data_manager = DataManager.get_instance()
            
            # 只检查数据库连接状态
            if not self._check_database_connection():
                logger.error("数据库连接失败")
                return False
            
            self.data_processor = StockDataProcessor()
            logger.info("股票处理器初始化成功")
            return True
            
        except Exception as e:
            logger.error(f"初始化股票处理器失败: {str(e)}")
            return False
    
    def _check_database_connection(self) -> bool:
        """检查数据库连接状态"""
        try:
            # 直接检查连接状态标识
            if not all([
                self.data_manager.redis.is_connected(),
                self.data_manager.postgres.is_connected()
            ]):
                return False
            return True
        except Exception as e:
            logger.error(f"数据库连接检查失败: {str(e)}")
            return False
    
    def close(self):
        """关闭处理器"""
        if self.data_manager:
            self.data_manager.close()
    
    def run_daily_update(self) -> bool:
        """运行每日数据更新任务"""
        try:
            logger.info("开始执行每日数据更新任务")
            
            # 1. 更新今日行情数据
            if not self.data_processor.update_newest_data('20250422'):
                logger.warning("更新今日行情数据失败")
            
            # 2. 运行数据管理器的每日任务
            # if not self.data_manager.run_daily_tasks():
            #     logger.warning("运行数据管理器每日任务失败")
            
            logger.info("每日数据更新任务执行完成")
            return True
            
        except Exception as e:
            logger.error(f"执行每日数据更新任务失败: {str(e)}")
            return False
        
    
    @staticmethod
    def schedule_daily_update():
        """设置每日更新任务的调度"""
        pass